<?php
namespace User\Model;

use Zend\Db\TableGateway\TableGateway;
/**
 * 数据库操作
 * @author Administrator
 *
 */
class UsersTable
{
	protected $tableGateway;
	
	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}
	
	public function getUser($id)
	{
		$id = (int)$id;
		$rowset = $this->tableGateway->select(array('id' => $id));
		$row = $rowset->current();
		if(!$row) {
			throw new \Exception("Could not find row {$id}");
		}
		return $row;		
	}
	
	public function saveUser(Users $user)
	{
		$data = array(
		    'username' => $user->username,
		    'password' => md5($user->password),
		    'real_name' => $user->realname,
		);
		$id = (int)$user->id;
		if ($id == 0) {
			$this->tableGateway->insert($data);
		} else {
			if ($this->getUser($id)) {
				$this->tableGateway->update($data, array('id' => $id));
			} else {
				throw new \Exception('User Does not exists');
			}
		}
	}
	
	public function deleteUser($id)
	{
		$this->tableGateway->delete(array('id' => $id));
	}
}
?>